package ar.com.cooker.services.tts;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import ar.com.cooker.services.util.PropertyManager;


public class GoogleTTS {
	
	
	public void generateSoundFile(String langCode,String text, String fileNameOut) throws TTSCookerException{
		
		List<StringBuilder> texts = new ArrayList<StringBuilder>();
		String tempPath = PropertyManager.getInstance().getPathToMp3Temp();
		boolean isOneFileOnly =false;
		int current =0;
		
		if(text.length()>100){
			
			String aux[] = text.split(" ");
			for (String string : aux) {
				if(texts.get(current)==null){
					texts.add(new StringBuilder(""));
				}
				int auxLegth = texts.get(current).length();
				if(auxLegth+1+string.length()<100){
					texts.get(current).append(" "+string);
				}else{
					current++;
					texts.add(new StringBuilder(string));
				}
			}
			
		}else{
			texts.add(new StringBuilder(text));
			isOneFileOnly=true;
		}
		
		UUID idOne = UUID.randomUUID();
		int fileNum = 0;
		String[] tempFilenames = new String[texts.size()];
		int i=0;
		for (StringBuilder sb : texts) {
			if(isOneFileOnly){
				tempFilenames[i] = fileNameOut;
			}else{
				tempFilenames[i] = tempPath+File.separator+"temp_"+fileNum+"_"+idOne.toString()+".mp3";
			}
			callGoogleTTSWithWGET(tempFilenames[i],langCode,sb.toString());
			i++;
		}
		if(!isOneFileOnly){
			//si son mas de uno mergeamos todos en uno y despues borramos los temporales
			mergeTempMP3s(tempFilenames,fileNameOut);
			//remove temp files
			for (String fileTemp : tempFilenames) {
				boolean success =false;
					 File f = new File(fileTemp);
				    if (f.exists() && f.canWrite()){
				          success = f.delete();
				          //TODO: Log si no se pudo borrar
				    }
			}
		}
	}
	
	private void mergeTempMP3s(String[] tempFilenames, String fileNameOut) throws TTSCookerException {
		
	     String command = PropertyManager.getInstance().getWrap();
	     StringBuilder files = new StringBuilder("");
	     for (String filename : tempFilenames) {
			files.append(filename);
			files.append(" ");
		}
	    command = command.replace("%files", files.toString().trim());
        command = command.replace("%output",fileNameOut);
        
        try {
			Runtime.getRuntime().exec(command);
		} catch (IOException e) {
			throw new TTSCookerException("Imposible ejecutar comando wrap: \n"+
					command+"\n . Error: "+e.getMessage(),e);
		}
	}

	private void callGoogleTTSWithWGET(String filename,String langCode,String text) throws TTSCookerException
    {
          String command = PropertyManager.getInstance().getWget();
          command = command.replace("%file", filename);
          command = command.replace("%lang",langCode);
          try {
			command = command.replace("%s",URLEncoder.encode(text,"UTF-8"));
		} catch (UnsupportedEncodingException e) {
			 throw new TTSCookerException("Imposible ejecutar URLEncoder, parametros: "
					 +text+"\n enc: UTF-8. Mensaje "+e.getMessage(),e);
		}
          try{        	  
              Runtime.getRuntime().exec(command);               
          }
          catch(Exception ex)
          {
        	  throw new TTSCookerException("imposible ejecutar comando wget.\n"
        			  +" comando: "+command+" .Error: "+ex.getMessage(),ex);
          }
    }
	
	
}
